package com.lemobar.pay.service.impl.alipay;

import com.lemobar.pay.model.PayRequest;
import com.lemobar.pay.model.PayResponse;
import com.lemobar.pay.model.alipay.request.AliPayTradeAppPayRequest;
import com.lemobar.pay.utils.JsonUtil;
import com.lemobar.pay.utils.MapUtil;
import com.lemobar.pay.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;

/**
 * Description: https://opendocs.alipay.com/apis/api_1/alipay.trade.app.pay
 */
@Slf4j
public class
AlipayAppServiceImpl extends AliPayServiceImpl {

    @Override
    public PayResponse pay(PayRequest request) {
        AliPayTradeAppPayRequest payRequest = new AliPayTradeAppPayRequest();
        payRequest.setAppId(aliPayConfig.getAppId());
        payRequest.setTimestamp(LocalDateTime.now().format(formatter));
        payRequest.setNotifyUrl(StringUtil.isEmpty(request.getNotifyUrl()) ? aliPayConfig.getNotifyUrl() : request.getNotifyUrl());

        AliPayTradeAppPayRequest.BizContent bizContent = new AliPayTradeAppPayRequest.BizContent();
        bizContent.setOutTradeNo(request.getOrderId());
        bizContent.setTotalAmount(String.valueOf(request.getOrderAmount()));
        bizContent.setSubject(request.getOrderName());

        payRequest.setBizContent(JsonUtil.toJsonWithUnderscores(bizContent).replaceAll("\\s*", ""));

        payRequest.setSign(AliPaySignature.sign(MapUtil.object2MapWithUnderline(payRequest), aliPayConfig.getPrivateKey()));

        PayResponse payResponse = new PayResponse();
        payResponse.setOrderInfo(MapUtil.toUrlWithSortAndEncode(MapUtil.removeEmptyKeyAndValue(MapUtil.object2MapWithUnderline(payRequest))));
        return payResponse;
    }
}
